package com.epro.dx.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.epro.dx.R;
import com.epro.dx.activity.coupon.adapter.MyCouponListAdapter;
import com.epro.dx.listenner.OnCouponExpiredListenner;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CouponError;
import com.weipu.common.facade.model.CouponModel;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.PreviewOrderModel;
import com.weipu.common.okhttp.JsonUtils;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

public class DiscountActivity extends BaseFragmentActivity {
    private static final String TAG = "DiscountActivity";
    private List<Lines> lines = new ArrayList<Lines>();
    // 商品订单信息集合
    private ArrayList<OrderProductModel> orderProductModels;
    private EditText couponEt;
    private Button couponApply;

    private ListView couponListView;

    private PreviewOrderModel previewOrderModel = new PreviewOrderModel();

    private ArrayList<CouponModel> couponList = new ArrayList<CouponModel>();
    private MyCouponListAdapter couponListAdapter;

    private String couponCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tracker tracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
        tracker.setScreenName(DiscountActivity.class.getSimpleName());
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
        // 隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 关联布局文件
        setContentView(R.layout.activity_discount);
        // 设置标题与返回按钮
        setTitleContent("Discount");
        setLeftBtnContent(true, -1);
        getIntentData(getIntent());
        intView();
        setListenner();
        if (null == couponList || couponList.size() == 0) {
            AsyncTaskUtil.executeTask(new UseableCoupon(null, false));
        } else {
            couponListAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取界面之间传递的数据
     *
     * @param intent
     */
    private void getIntentData(Intent intent) {
        if (null != intent) {
            couponList.clear();
            ArrayList<CouponModel> list = intent
                    .getParcelableArrayListExtra("UseableCoupon");
            if (list != null) {
                couponList.addAll(list);
            }
            orderProductModels = intent
                    .getParcelableArrayListExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP);
            couponCode = intent.getStringExtra("CouponCode");
        }
    }

    /**
     * 初始化控件
     */
    private void intView() {
        couponEt = (EditText) findViewById(R.id.coupon_code_et);
        if (null != couponCode) {
            couponEt.setText(couponCode);
        }
        couponApply = (Button) findViewById(R.id.coupon_code_apply_btn);
        couponListView = (ListView) findViewById(R.id.useable_coupon_list);
        couponListAdapter = new MyCouponListAdapter(this, couponList);
        couponListView.setAdapter(couponListAdapter);
    }

    /**
     * 事件监听
     */
    private void setListenner() {
        couponApply.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String coupon = couponEt.getText().toString().trim();
                if (!TextUtils.isEmpty(coupon)) {
                    AsyncTaskUtil.executeTask(new UseableCoupon(couponEt
                            .getText().toString().trim(), true));
                } else {
                    AlertToast.alert(DiscountActivity.this,
                            getString(R.string.coupon_not_null));
                }

            }
        });
        couponListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                if (null == couponList || couponList.size() <= position) {
                    return;
                }

                //如果优惠卷失效了 ，则弹出提示
                if (Boolean.parseBoolean(StringUtil.getConfig("couponError", false + ""))) {
                    showToast(getResources().getString(R.string.coupon_error));
                    return;
                }

                Intent intent = new Intent();
                intent.putExtra("CouponCode", couponList.get(position)
                        .getCouponCode());
                intent.putExtra("IsCouponCode", false);
                setResult(ServerConstant.Parameter.CHOOSE_COUPON_CODE, intent);
                finish();
            }
        });

        couponListAdapter
                .setOnCouponExpiredListenner(new OnCouponExpiredListenner() {
                    public void onExpired(int position) {
                        if (null != couponList && couponList.size() > position) {
                            couponList.remove(position);
                            couponListAdapter.notifyDataSetChanged();
                        }
                    }

                    ;
                });
    }

    /**
     * 获取可用Coupon
     *
     * @author hf
     */
    class UseableCoupon extends BaseNeedReLoginTask {
        private String couponCode;
        private boolean isCheckCoupon;

        public UseableCoupon(String couponCode, boolean isCheckCoupon) {
            this.couponCode = couponCode;
            this.isCheckCoupon = isCheckCoupon;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(couponListView);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            if (null != orderProductModels) {
                Logger.i(TAG,
                        "orderProductModels() " + orderProductModels.size());
                lines.clear();
                for (int i = 0; i < orderProductModels.size(); i++) {
                    OrderProductModel opm = orderProductModels.get(i);
                    Lines li = new Lines();
                    li.setSku(opm.getSku());
                    li.setSellingPrice(opm.getPrice());
                    li.setQty(opm.getQuantity());
                    lines.add(li);
                }
            }

            try {
                previewOrderModel = ProviderFactory
                        .createCouponServiceProvider().PreviewOrder(
                                ActivityUtil.getCustomerID().intValue(), "USD",
                                0, lines, couponCode, null, ActivityUtil.getCustomerToken(), null);
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (!isFinishing()) {
                // hideWaitingDialog();
                hideAllLayout(couponListView);
                if ("0".equals(result)) {
                    if (isCheckCoupon) {
                        if (null != previewOrderModel) {
                            CouponError couponError = previewOrderModel
                                    .getCouponError();
                            if (null != couponError) {
                                if ("80330108".equals(couponError
                                        .getErrorCode())) {
                                    AlertToast
                                            .alert(DiscountActivity.this,
                                                    getString(R.string.invalid_Coupon_Code));
                                } else {
                                    AlertToast.alert(DiscountActivity.this,
                                            couponError.getLongMessage());
                                }
                            } else {
                                Intent intent = new Intent();
                                intent.putExtra("CouponCode", couponCode);
                                intent.putExtra("IsCouponCode", true);
                                setResult(
                                        ServerConstant.Parameter.CHOOSE_COUPON_CODE,
                                        intent);
                                finish();
                            }
                        }

                    } else {
                        if (null != previewOrderModel) {
                            if (null != couponList) {
                                couponList.clear();
                                if (previewOrderModel.getUsableCoupons() != null) {
                                    couponList.addAll(previewOrderModel
                                            .getUsableCoupons());
                                    couponListAdapter.notifyDataSetChanged();
                                }
                            }
                        }

                    }

                } else if (!isRelogin) {
                    AlertToast.alert(DiscountActivity.this,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }
        }

        @Override
        protected Context setContext() {
            return DiscountActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new UseableCoupon(couponCode, isCheckCoupon);
        }

    }

    /**
     * 校验Coupon是否有效
     *
     * @author hf
     */
    class CheckCouponEnable extends BaseNeedReLoginTask {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                previewOrderModel = ProviderFactory
                        .createCouponServiceProvider().PreviewOrder(
                                ActivityUtil.getCustomerID().intValue(), "USD",
                                0, new ArrayList<Lines>(),
                                couponEt.getText().toString(), null, ActivityUtil.getCustomerToken(), null);
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if ("0".equals(result)) {
                Intent intent = new Intent();
                intent.putExtra("CouponCode", couponEt.getText());
                intent.putExtra("IsCouponCode", true);
                // intent.putExtra("PreviewOrderModel", previewOrderModel);
                setResult(ServerConstant.Parameter.CHOOSE_COUPON_CODE, intent);
                finish();
            } else if (!isRelogin) {
                AlertToast.alert(DiscountActivity.this,
                        ServerConstant.ReturnCode.MESSAGEMAP.get(result));
            }
        }

        @Override
        protected Context setContext() {
            return DiscountActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new CheckCouponEnable();
        }

    }
}
